<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { login, fetchCaptchaAPI,register,sendEmailCaptchaAPI } from '@/api/LoginAndRegistration.js'
import router from "@/router/index.js";

const form = ref({
  username: '',
  password: '',
  captcha: ''
})
const registerForm = ref({
  username: '',
  password: '',
  email: '',
  captcha: ''
})
// 定义图片列表
const images = ref([
  { src: 'src/assets/Photo/01.jpg', alt: 'Image 1' },
  { src: 'src/assets/Photo/02.jpg', alt: 'Image 2' },
  { src: 'src/assets/Photo/03.jpg', alt: 'Image 3' },
  { src: 'src/assets/Photo/04.jpg', alt: 'Image 4' },
])
const formRef = ref(null)
const userStore = useUserStore()
const showLogin = ref(false) // 控制登录弹窗的显示隐藏
const showRegister = ref(false) // Controls registration modal visibility


// 用于存储验证码图片的 URL
const captchaUrl = ref('')
const countdown = ref(0)

let timer = null

// 页面加载时获取验证码
const fetchCaptcha = () => {
  console.log('Fetching captcha...')
  fetchCaptchaAPI().then((url) => {
    captchaUrl.value = url
    console.log('Captcha URL:', url)
  }).catch((err) => {
    ElMessage.error('Failed to load captcha')
  })
}

// 登录操作
const handleLogin = () => {
  login(form.value).then((res) => {
    if (res.data.code === 200) {
      userStore.setUserId(res.data.data.userId)
      userStore.setToken(res.data.data.token)
      userStore.setUserName(res.data.data.userName)
      userStore.setAvatar(res.data.data.avatar)
      userStore.setNickname(res.data.data.nickname)
      console.log(userStore.nickname)


      showLogin.value = false // 成功登录后关闭弹窗

      form.value = {
        username: '',
        password: '',
        captcha: ''
      }
      router.push('/layout') // 跳转到首页
    } else {
      ElMessage.error(res.data.msg)


    }
  }).catch((err) => {
    ElMessage.error(err.message)
  })
}

// Register functionality
const handleRegister = () => {
  register(registerForm.value).then((res) => {
    if (res.data.code === 200) {
      ElMessage.success("注册成功!")
      showRegister.value = false
      showLogin.value = true
      registerForm.value = { username: '', password: '', email: '', captcha: '' }
    } else {
      ElMessage.error(res.data.msg)
    }
  }).catch((err) => {
    ElMessage.error(err.msg)
  })
}

// Send email verification code
const sendEmailCaptcha = () => {
  if (!registerForm.value.email) {
    ElMessage.error("请先输入您的邮箱地址！")
    return
  }
  startCountdown()
  sendEmailCaptchaAPI(registerForm.value.email).then(() => {
    ElMessage.success("验证码已发送到您的邮箱！")

  }).catch(() => {
    ElMessage.error("发送验证码失败")
  })
}

// Start the countdown timer for 120 seconds
const startCountdown = () => {
  countdown.value = 120
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}
// 页面加载时自动获取验证码
fetchCaptcha()
</script>

<template>
  <div style="width:1330px;margin-top: 1%;margin-left: -2%; ">
    <el-carousel height="600px" :autoplay="true" :interval="3000">
      <el-carousel-item v-for="(item, index) in images" :key="index">
        <img :src="item.src" :alt="item.alt" style="width: 100%; height: 100%;" />
      </el-carousel-item>
    </el-carousel>
  </div>

  <div class="top-bar">
    <p  @click="showLogin = true" class="login-button">登录</p>
  </div>

  <!-- 登录弹窗 -->
  <el-dialog v-model="showLogin" title="登录" style="width: 400px;height: 300px;">
    <el-form :model="form" ref="formRef" class="login-form">
      <el-form-item prop="username" label="用户名">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item prop="password" label="密&nbsp&nbsp&nbsp&nbsp码">
        <el-input type="password" v-model="form.password" placeholder="请输入密码" show-password />
      </el-form-item>
      <!-- 验证码部分 -->
      <el-form-item label="验证码">
        <div class="captcha-container">
          <!-- 输入框在左 -->
          <el-input v-model="form.captcha" placeholder="请输入验证码" class="captcha-input" />
          <!-- 验证码图片在右 -->
          <img v-if="captchaUrl" :src="captchaUrl" alt="Captcha" @click="fetchCaptcha" class="captcha-img" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button style=" width: 200px;margin-left: 23%;" type="primary" @click="handleLogin">登录</el-button>
      </el-form-item>
    </el-form>
    <p @click="showRegister = true; showLogin = false" style="cursor: pointer;text-align: center;"><i>还没有账号?，立即注册</i></p>
  </el-dialog>

  <!-- 注册弹窗 -->
  <el-dialog v-model="showRegister" title="注册" width="400px">
    <el-form :model="registerForm" ref="formRef" class="login-form">
      <el-form-item prop="username" label="用户名">
        <el-input v-model="registerForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item prop="password" label="密&nbsp&nbsp&nbsp&nbsp码">
        <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" show-password />
      </el-form-item>
      <el-form-item prop="email" label="邮&nbsp&nbsp&nbsp&nbsp箱">
        <div class="captcha-container">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" class="captcha-input" />
          <el-button type="primary" @click="sendEmailCaptcha" :disabled="countdown > 0">
            {{ countdown > 0 ? countdown + '秒后重发' : '发送验证码' }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="验证码">
        <el-input v-model="registerForm.captcha" placeholder="请输入验证码" />
      </el-form-item>
      <el-form-item>
        <el-button style=" width: 200px;margin-left: 23%;"  type="primary" @click="handleRegister">注册</el-button>
      </el-form-item>
      <p   @click="showLogin = true; showRegister = false" style="cursor: pointer; text-align: center;"><i>已有账户?，立即登陆</i></p>
    </el-form>
  </el-dialog>

  <div>
    <div style="margin-top: 50px;">
      <div style="text-align: center; color: rgb(112, 184, 9);">
        <h1 style="text-decoration: underline; font-weight: bold; font-size: 40px;">项目背景</h1>
      </div>
      <div style="font-size: 20px;">
        <p>&emsp;&emsp;在全球气候变化和资源紧缺以及环境污染的背景下，推动可持续发展和环保理念已成为社会的迫切需求。日常生活中的碳排放和资</p>
        <p>源浪费对环境造成了巨大影响。为了应对这些挑战，许多国家和企业纷纷倡导绿色生活方式。然而，缺乏便利的平台和有效的激励机制使得</p>
        <p>个人在践行环保行为时面临诸多障碍。</p>
      </div>
    </div>
    <div style="display: flex; justify-content: space-around; margin-top: 50px;margin-left: -5%">
        <img style="width: 550px;height:350px" src="@/assets/Photo/环境污染.png" alt="环境污染">
       <img  style="width: 550px;height:350px" src="@/assets/Photo/空气污染.png" alt="环境污染">
    </div>
    <div style="display: flex; justify-content: space-around; margin-top: 50px;margin-left: -5%">
      <img style="width: 550px;height:350px" src="@/assets/Photo/动物污染.png" alt="环境污染">
      <img  style="width: 550px;height:350px" src="@/assets/Photo/城市污染.png" alt="环境污染">
    </div>


    <div style="margin-top: 50px; ">
      <div style="text-align: center;color: rgb(112, 184, 9);">
        <h1 style="text-decoration: underline; font-weight: bold;font-size: 40px;">我们的初衷</h1>

      </div>
      <div style="font-size: 20px;">
        <p>&emsp;&emsp; 我们的初衷是通过技术手段推动绿色生活方式的普及。它提供了二手物品交换、环保产品购买、碳足迹计算等功能，方便用户实现</p>
        <p>资源的循环利用，减少日常生活中的浪费。平台内设有连续签到和奖励机制，激励用户采取环保行为，如选择低碳出行、减少能源消耗等。</p>
        <p>平台旨在帮助个人降低碳排放，实现可持续发展，最终共同守护地球生态环境。</p>
      </div>
    </div>

  </div>

</template>

<style scoped>
.demonstration {
  color: var(--el-text-color-secondary);
}

.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 150px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.top-bar {
  position: relative;
  right:500%;
  top: 5%;
  color: white;
  width: 2.5em;
/* 鼠标悬停时文字颜色变化 */
  :hover {
    color: #0738e1;
  }
  /*鼠标形状*/
  cursor: pointer;
  font-weight: bold;
  font-size: 20px;

}

/* 登录表单的整体样式 */
.login-form {
  display: flex;
  flex-direction: column;
}

/* 验证码容器样式 */
.captcha-container {
  display: flex;
  align-items: center;
}

/* 验证码输入框样式 */
.captcha-input {
  flex: 1;
  margin-right: 10px;
}

/* 验证码图片样式 */
.captcha-img {
  width: 100px;
  height: 30px;
  border: 1px solid #ccc;
  cursor: pointer;
}
</style>
